/**
 * Copyright (c) 2010, Microsoft Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *       Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *       
 *       Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *       
 *       Neither the name of Microsoft nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Microsoft ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Microsoft BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System.Linq;
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace WebRole
{
    public class WebRole : RoleEntryPoint
    {
        private XDrives m_XDrive = new XDrives();

        /// <summary>
        /// Called by Windows Azure to initialize the role instance. 
        /// </summary>
        /// <returns>True if initialization succeeds, False if it fails.</returns>
        public override bool OnStart()
        {
            Trace.TraceInformation("RoleEntryPoint.OnStart()");

            ConfigDiagnostics();
            m_XDrive.MountXDrives();

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            return base.OnStart();
        }

        /// <summary>
        /// Called by Windows Azure when the role instance is to be stopped.
        /// </summary>
        public override void OnStop()
        {
            Trace.TraceInformation("RoleEntryPoint.OnStop()");
            m_XDrive.UnmountXDrives();

            base.OnStop();
        }


        private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
        {
            // If a configuration setting is changing
            if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
            {
                // Set e.Cancel to true to restart this role instance
                e.Cancel = true;
            }
        }

        /// <summary>
        /// Configure diagnostics for a Windows Azure role instance
        /// </summary>
        private void ConfigDiagnostics()
        {
            try
            {
                string transferPeriod = RoleEnvironment.GetConfigurationSettingValue("ScheduledTransferPeriodInSeconds");
                if (!string.IsNullOrEmpty(transferPeriod))
                {
                    // Create policy to transfer logs every minutes outsitde Widnows Azure VM
                    DiagnosticMonitorConfiguration dmc = DiagnosticMonitor.GetDefaultInitialConfiguration();
                    dmc.Logs.ScheduledTransferPeriod = TimeSpan.FromSeconds(Int32.Parse(transferPeriod));

                    // Configure log level.
                    string logLevel = RoleEnvironment.GetConfigurationSettingValue("LogLevel");
                    if (logLevel.Equals("Critical"))
                    {
                        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Critical;
                    }
                    else if (logLevel.Equals("Error"))
                    {
                        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Error;
                    }
                    else if (logLevel.Equals("Information"))
                    {
                        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
                    }
                    else if (logLevel.Equals("Undefined"))
                    {
                        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;
                    }
                    else if (logLevel.Equals("Verbose"))
                    {
                        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
                    }
                    else if (logLevel.Equals("Warning"))
                    {
                        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Warning;
                    }

                    DiagnosticMonitor.Start("WindowsAzureStorageConnectionString", dmc);
                    Trace.WriteLine("Diagnostics Started", "Information");
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Unable to start Diagnostics: " + ex.Message);
            }
        }
    }
}
